package com.simin.mall.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;


import com.simin.base.appnet.netother.RxSubscriber;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by wsm on 2024/9/9.
 * <p>
 */
public abstract class BaseFragment extends Fragment {
    public static final String TAG="BaseFragment";

    public ActivityResultLauncher<Intent> register;//选择回调

    //rxjava
    public CompositeSubscription compositeSubscription = new CompositeSubscription();//管理所有的订阅
    public AudioManager mAudioManager;
    private VolumeChangeObserver mVolumeChangeObserver;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(setContentViewID(), container, false);
        initView(view);
        loadData();
        return view;
    }


    protected abstract int setContentViewID();

    protected abstract void initView(View view);

    protected abstract void loadData();

    /**
     * 检测网络是否可用
     */
    public boolean isNetworkConnected() {

        ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        return ni != null && ni.isConnectedOrConnecting();
    }

    //初始化跳转Activity回调数据
    public void initactivityResult() {
        // 下一个Activity回退后 在此获取返回的值
        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result != null) {
                    Intent intent = result.getData();
                    if (intent != null && result.getResultCode() == Activity.RESULT_OK) {
                        onActivityForResult(intent);
                    }
                }
            }
        });
    }

    //获取下一个activity回调数据
    public void onActivityForResult(Intent intent) {

    }

    /**
     * 初始化音量
     */
    public void initAudioManager() {
        mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
        mVolumeChangeObserver = new VolumeChangeObserver(new Handler());
        getContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, mVolumeChangeObserver);
    }

    // 音量销毁方法
    public void releaseVolume() {
        if (mVolumeChangeObserver!=null){
            getContext().getContentResolver().unregisterContentObserver(mVolumeChangeObserver);
        }
    }

    // 音量变化的观察者类
    private class VolumeChangeObserver extends ContentObserver {
        public VolumeChangeObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            // 处理音量变化的逻辑
            int currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            // ...
            onVolumeChange(currentVolume);
        }
    }

    /**
     * 音量监听
     *
     * @param currentVolume
     */
    public void onVolumeChange(int currentVolume) {

    }

    @Override
    public void onResume() {
        super.onResume();
    }


    @Override
    public void onPause() {
        super.onPause();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        detachCompositeSubscription();//取消所有的订阅
        releaseVolume();
    }

    /**
     * 建立Composite订阅管理，取消所有订阅  rxjava中使用
     */
    public void detachCompositeSubscription() {
        if (compositeSubscription.hasSubscriptions()) {
            //取消注册，以避免内存泄露
            compositeSubscription.unsubscribe();
        }
    }


    protected <T> void addSubscription(Observable<T> observable, RxSubscriber<T> subscriber) {
        //管理所有的订阅
        compositeSubscription = new CompositeSubscription();
        compositeSubscription.add(observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(subscriber));
    }
}
